﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Xml;
using System.Threading;
using FinPlusInterfaces;
using FinPlusAssembler;
using FinPlusCompCore;

namespace FinPlusCompTDD
{
    //TODO under construction
    public class FinPlusDPodLogger : FinPlusComponent, IFinPlusConnect
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }
        public override IPods Adapter { get { return _adapter.ToPods(); } }
        public bool CanWrite { get { return _conn.CanWrite; } }

        private readonly IFinPlusConnect _conn;
        private readonly IDPods _adapter;
        private XmlDocument _xmlDoc;
        private XmlNode _xmlTran;
        private string _name, _path;

        //construct
        public FinPlusDPodLogger(IFinPlusConnect conn, string name, Env enabled = Env.test)
        {
            if (!Env.Equals(enabled))
                return; 

            _conn = conn;
            _name = name;
            _path = string.Format("{0}{1}-{2}.{3}", Paths.Values["FolderLogs"], name, DateTime.Now.ToFileTime(), FileType.log);
            _conn.DPods().PodChanged += Pod_Changed;
            _adapter = IOC.New<IDPods>(conn.DPods().ToPods().Clone());
            _xmlDoc = _adapter.ToPods().ToXmlDoc("root/data");
            _xmlDoc.SelectSingleNode("root", null).AppendChild(_xmlTran = _xmlDoc.CreateNode(XmlNodeType.Element, "transactions", null));
        }

        //common control interface
        public override void Dispose()
        {
            if (_conn != null)
                _conn.Dispose();
            _xmlDoc.Save(_path);
        }

        //public
        public IDPods DPods() { return _conn.DPods(); }

        public IPods Pods() { return _conn.DPods().ToPods(); }

        //events
        private void Pod_Changed(object s, PropertyChangedEventArgs a)
        {
            var dpod = (IDPod)s;
            var tran = new List<IBean>();
            tran.Add(dpod.GetBean(a.PropertyName));
            tran.Add(IOC.New<IBean>(0, -1, BeanField.LinkedId.ToString(), dpod.GetBean(BeanField.Id.ToString()).Value, DateTime.Now, ""));
            tran.Add(IOC.New<IBean>(0, -1, BeanField.ThreadId.ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now, ""));
            IOC.New<IPod>(tran).ToXml(_xmlDoc, "root/transactions");
        }
    }
}
